'''
程序名: 屏幕共享网页服务
作者: SinoLee
日期: 2024-09-18
版本: 0.2
'''
import os
import time
from fastapi import FastAPI, Request, WebSocket
# from fastapi.templating import Jinja2Templates
import pyautogui
from fastapi.responses import StreamingResponse,FileResponse
from PIL import Image
from io import BytesIO
# import websocket

app = FastAPI()

# templates=Jinja2Templates(directory="templates") # 指定模板文件目录
index_file_abspath=os.path.abspath(os.path.join(os.path.dirname(__file__), "templates","index.html")) #打包时需要绝对路径
# templates=Jinja2Templates(directory=".\\templates") # 指定模板文件目录
print(index_file_abspath)

def capture_screen() -> bytes:
    try:
        screenshot = pyautogui.screenshot()
        img_byte_arr = BytesIO()
        screenshot.save(img_byte_arr, format='PNG')
    except:
        img_byte_arr=None
        print("无法截取图片")
    img_byte_arr = img_byte_arr.getvalue()  # 获取字节流
    return img_byte_arr

def generate_images():
    while True:
        frame = capture_screen()
        yield (b'--frame\r\n'
               b'Content-Type: image/png\r\n\r\n' + frame)  # 直接 yield 字节流
        time.sleep(0.02)  # 每0.02秒捕获一次屏幕
    
@app.get("/")
def read_root():
    return FileResponse(index_file_abspath)

@app.get("/stream")
async def stream_images():
    return StreamingResponse(generate_images(), media_type='multipart/x-mixed-replace; boundary=frame')

# websocket实现
@app.get("/ws")
async def ws_trans():
    pass


if __name__ == "__main__":
    import uvicorn
    print("Starting service...")
    uvicorn.run(app=app, host="0.0.0.0", port=5000, reload=False,log_level="warning")
    print("Serving at http://0.0.0.0:5000")